import React, { useEffect, useState } from 'react';
import { SpinLoading } from 'antd-mobile';
import { useNavigate, useSearchParams } from 'react-router-dom';
import './oauth.module.css';
import { 
  mockGiteeAccessToken, 
  mockGiteeUserInfoAPI, 
  mockGiteeLoginSuccess 
} from '../../data/gitee';

const Oauth: React.FC = () => {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const [message, setMessage] = useState('正在处理授权...');

  useEffect(() => {
    handleOAuthCallback();
  }, []);

  // 处理 OAuth 回调
  const handleOAuthCallback = async () => {
    try {
      // 获取 URL 参数
      const code = searchParams.get('code');
      const state = searchParams.get('state');
      const error = searchParams.get('error');

      // 检查是否有错误
      if (error) {
        setMessage('授权失败：' + error);
        setTimeout(() => {
          navigate('/login');
        }, 2000);
        return;
      }

      // 检查必要参数
      if (!code || !state) {
        setMessage('授权参数不完整');
        setTimeout(() => {
          navigate('/login');
        }, 2000);
        return;
      }

      // 验证 state 防止 CSRF 攻击
      const savedState = localStorage.getItem('gitee_state');
      if (state !== savedState) {
        setMessage('授权验证失败');
        setTimeout(() => {
          navigate('/login');
        }, 2000);
        return;
      }

      // 清除存储的 state
      localStorage.removeItem('gitee_state');

      setMessage('正在获取用户信息...');

      // 使用授权码获取 access_token
      const tokenResponse = await mockGiteeAccessToken();
      
      if (!tokenResponse.access_token) {
        throw new Error('获取访问令牌失败');
      }

      setMessage('正在获取用户信息...');

      // 使用 access_token 获取用户信息
      const userInfo = await mockGiteeUserInfoAPI();

      // 模拟登录成功
      const userData = await mockGiteeLoginSuccess(userInfo);

      // 存储到 localStorage
      localStorage.setItem('userToken', userData.token);
      localStorage.setItem('userData', JSON.stringify(userData.user));
      localStorage.setItem('loginType', 'gitee');

      setMessage('登录成功，正在跳转...');
      
      // 延迟跳转，让用户看到成功消息
      setTimeout(() => {
        window.location.href = '/chat'; // 跳转到聊天页面或其他主页面
      }, 1500);

    } catch (error) {
      console.error('OAuth 处理失败:', error);
      setMessage('登录失败，请重试');
      setTimeout(() => {
        navigate('/login');
      }, 2000);
    }
  };



  return (
    <div className="oauth-container">
      <div className="oauth-content">
        <div className="loading-icon">
          <SpinLoading color="primary" />
        </div>
        <div className="loading-text">
          {message}
        </div>
      </div>
    </div>
  );
};

export default Oauth;
